package com.cuiyongzhi.web.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesUtil {
	
	// 默认资源文件名称
	private static final String NAME = "/wechat.properties";
	
	private static Properties prop;
	
	public static synchronized Properties getInstance() {
		Properties prop = new Properties();
        String savePath = PropertiesUtil.class.getResource(NAME).getPath();
        InputStream is;
		try {
			is = new BufferedInputStream(new FileInputStream(savePath));
			prop.load(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return prop;
	}


	/**
	 * 获取属性值
	 * @param key：根据key获取value
	 * @return
	 */
	public static String getProperty(String key) {

		return prop.getProperty(key);

	}

	/**
	 * 
	 * 将文件加载到内存中，在内存中修改key对应的value值，再将文件保存
	 * 没有key值存在时，会新增
	 */
	public static void setProper(String key, String value, String file) {
		try {
			prop.setProperty(key, value);
			String savePath = PropertiesUtil.class.getResource(file).getPath();
			FileOutputStream fos = new FileOutputStream(savePath);
			prop.store(fos,null);
			fos.close();
			fos.flush();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();

		}
	}
}
